# 利用中点算法绘制两条直线，分别是：L1(Point(20, 10), Point(100, 180))， L2(Point(-50, 100), Point(100, -50))。

import numpy as np
import matplotlib.pyplot as plt

width = 480
height = 480


def axis_shift(x, y):
    # 到坐标原点
    x = x + width // 2
    y = height // 2 - y
    return x, y


def MPLine(x1, y1, x2, y2, img, color=(255, 0, 0)):
    # 确保x1在左，x2在右
    if x1 > x2:
        x1, y1, x2, y2 = x2, y2, x1, y1

    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    if dx >= dy:    # x 主位移
        dx = x2 - x1
        dy = y2 - y1

        if dy >= 0: # 增函数（k为0-1）
            e = dx - 2 * dy
            up_inc = 2 * dx - 2 * dy
            down_inc = -2 * dy
            y = y1
            for x in range(x1, x2 + 1):
                img[y, x, :] = color
                if e < 0:
                    y += 1
                    e += up_inc
                else:
                    e += down_inc
        else:   # 减函数（k为负）
            e = -dx - 2 * dy
            up_inc = -2 * dx - 2 * dy
            down_inc = -2 * dy
            y = y1
            for x in range(x1, x2 + 1):
                img[y, x, :] = color
                if e > 0:
                    y -= 1
                    e += up_inc
                else:
                    e += down_inc


# 加载或创建一个图像
img = np.zeros((height, width, 3), dtype=np.uint8)  # 创建一个256x256的黑色画布

# 绘制线段
MPLine(*axis_shift(20, 10), *axis_shift(200, 80), img, (255,255,255))
MPLine(*axis_shift(-20, 10), *axis_shift(200, -80), img, (255,0,0))
MPLine(*axis_shift(-20, 10), *axis_shift(200, 10), img, (255,255,0))


# 显示图像
plt.imshow(img)
plt.show()
